Python argparse:如何在帮助文本中插入换行符? 您所在的位置:网站首页 python args default Python argparse:如何在帮助文本中插入换行符?

Python argparse:如何在帮助文本中插入换行符?

#Python argparse:如何在帮助文本中插入换行符?| 来源: 网络整理| 查看: 265

I've faced similar issue (Python 2.7.6). I've tried to break down description section into several lines using RawTextHelpFormatter:

parser = ArgumentParser(description="""First paragraph Second paragraph Third paragraph""", usage='%(prog)s [OPTIONS]', formatter_class=RawTextHelpFormatter) options = parser.parse_args()

And got:

usage: play-with-argparse.py [OPTIONS] First paragraph Second paragraph Third paragraph optional arguments: -h, --help show this help message and exit

So RawTextHelpFormatter is not a solution. Because it prints description as it appears in source code, preserving all whitespace characters (I want to keep extra tabs in my source code for readability but I don't want to print them all. Also raw formatter doesn't wrap line when it is too long, more than 80 characters for example).

Thanks to @Anton who inspired the right direction above. But that solution needs slight modification in order to format description section.

Anyway, custom formatter is needed. I extended existing HelpFormatter class and overrode _fill_text method like this:

import textwrap as _textwrap class MultilineFormatter(argparse.HelpFormatter): def _fill_text(self, text, width, indent): text = self._whitespace_matcher.sub(' ', text).strip() paragraphs = text.split('|n ') multiline_text = '' for paragraph in paragraphs: formatted_paragraph = _textwrap.fill(paragraph, width, initial_indent=indent, subsequent_indent=indent) + '\n\n' multiline_text = multiline_text + formatted_paragraph return multiline_text

Compare with the original source code coming from argparse module:

def _fill_text(self, text, width, indent): text = self._whitespace_matcher.sub(' ', text).strip() return _textwrap.fill(text, width, initial_indent=indent, subsequent_indent=indent)

In the original code the whole description is being wrapped. In custom formatter above the whole text is split into several chunks, and each of them is formatted independently.

So with aid of custom formatter:

parser = ArgumentParser(description= """First paragraph |n Second paragraph |n Third paragraph""", usage='%(prog)s [OPTIONS]', formatter_class=MultilineFormatter) options = parser.parse_args()

the output is:

usage: play-with-argparse.py [OPTIONS] First paragraph Second paragraph Third paragraph optional arguments: -h, --help show this help message and exit


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有